

package top.continew.admin.question.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import top.continew.admin.question.dify.workflow.QuestionWorkflow;
import top.continew.admin.question.dify.workflow.req.QuestionSummaryReq;
import top.continew.admin.question.dify.workflow.resp.QuestionSummaryResp;
import top.continew.admin.question.mapper.LearningSummaryMapper;
import top.continew.admin.question.model.LearningSummary;
import top.continew.admin.question.model.question.UserDoQuestionSet;
import top.continew.admin.question.service.LearningSummaryService;
import top.continew.admin.question.user.service.IUserQuestionService;

import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;

/**
 * 学习总结服务实现类
 */
@Slf4j
@Service
public class LearningSummaryServiceImpl extends ServiceImpl<LearningSummaryMapper, LearningSummary> implements LearningSummaryService {

    @Autowired
    private IUserQuestionService iUserQuestionService;

    @Override
    public LearningSummary generateSummary(Long questionSetId,
                                           Long userId,
                                           String questionAndAnswer,
                                           String knowledge) throws Exception {
        UserDoQuestionSet userDoQuestionSet = iUserQuestionService.getUserDoQuestionSet(userId, String
            .valueOf(questionSetId));
        if (questionAndAnswer == null) {
            return null;
        }
        if (userDoQuestionSet == null) {
            log.warn("用户做题记录不存在，用户ID: {}, 做题记录ID: {}", userId, questionSetId);
            return null;
        }
        log.info("开始生成学习总结，用户做题记录ID: {}, 用户ID: {}", userDoQuestionSet.getId(), userId);
        Long userDoQuestionSetId = userDoQuestionSet.getId();
        // 检查是否已存在该记录的学习总结
        LearningSummary existingSummary = getByUserDoQuestionSetId(userId, questionSetId);
        if (existingSummary != null) {
            log.info("该做题记录已有学习总结，直接返回现有结果");
            return existingSummary;
        }

        // 准备请求参数
        QuestionSummaryReq req = new QuestionSummaryReq();
        req.setQuestionAndAnswer(questionAndAnswer);
        req.setKnowledge(knowledge);

        // 调用AI工作流生成学习总结
        QuestionSummaryResp summaryResp = QuestionWorkflow.questionSummaryWorkflow(req);
        log.info("AI生成学习总结完成");

        // 创建并保存学习总结
        LearningSummary summary = new LearningSummary();
        summary.setUserDoQuestionSetId(userDoQuestionSetId);
        summary.setQuestionSetId(questionSetId);
        summary.setUserId(userId);
        summary.setSummarize(summaryResp.getSummarize());
        summary.setOverallAssessment(summaryResp.getOverallAssessment());

        // 处理学习建议
        if (summaryResp.getLearningSuggestions() != null && !summaryResp.getLearningSuggestions().isEmpty()) {
            summary.setLearningSuggestions(JSON.toJSONString(summaryResp.getLearningSuggestions()));
        }

        // 处理推荐学习
        if (summaryResp.getRecommendedLearning() != null && !summaryResp.getRecommendedLearning().isEmpty()) {
            summary.setRecommendedLearning(JSON.toJSONString(summaryResp.getRecommendedLearning()));
        }

        summary.setDate(LocalDateTime.now());

        // 保存到数据库
        save(summary);
        log.info("学习总结已生成并保存，ID: {}", summary.getId());

        return summary;
    }

    @Async
    @Override
    public CompletableFuture<LearningSummary> generateSummaryAsync(Long questionSetId,
                                                                   Long userId,
                                                                   String questionAndAnswer,
                                                                   String knowledge) {
        try {
            LearningSummary summary = generateSummary(questionSetId, userId, questionAndAnswer, knowledge);
            return CompletableFuture.completedFuture(summary);
        } catch (Exception e) {
            log.error("异步生成学习总结失败", e);
            CompletableFuture<LearningSummary> future = new CompletableFuture<>();
            future.completeExceptionally(e);
            return future;
        }
    }

    @Override
    public LearningSummary getByUserDoQuestionSetId(Long userId, Long questionSetId) {
        UserDoQuestionSet userDoQuestionSet = iUserQuestionService.getUserDoQuestionSet(userId, String
            .valueOf(questionSetId));
        if (userDoQuestionSet == null) {
            log.warn("用户做题记录不存在，用户ID: {}, 做题记录ID: {}", userId, questionSetId);
            return null;
        }
        return getOne(new LambdaQueryWrapper<LearningSummary>()
            .eq(LearningSummary::getUserDoQuestionSetId, userDoQuestionSet.getId())
            .last("LIMIT 1"));
    }
}